package com.lyy.system.controller;

import com.lyy.common.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.*;

/**
 * <p>上传相关接口
 *
 * @author HuYong
 * @since 2019-06-17
 */
@Slf4j
@RestController
@RequestMapping("/upload")
public class UploadController {

    /**
     * /upload/uploadPhoto 上传图片
     *
     * @param file 文件
     * @param type 类型
     */
    @PostMapping("/uploadPhoto")
    public Map<String, Object> uploadPhoto(String type, MultipartFile file) {
        AssertUtils.notNull(type, "类型不能为空");
        AssertUtils.isTrue(null == file, "上传文件为空");
        String timePath = Constants.getUploadUrl().get(type);
        AssertUtils.notNull(timePath, "类型错误");
        String name = file.getOriginalFilename();
        String fileExt = Objects.requireNonNull(name).substring(name.lastIndexOf(".") + 1).toLowerCase();
        String fileName = System.currentTimeMillis() + "_" + new Random().nextInt(1000) + "." + fileExt;
        boolean flag;
        try {
            flag = FileUtils.writeFileToLocal(timePath, fileName, file.getInputStream());
        } catch (IOException e) {
            log.info("上传文件发生异常::{}", e.getMessage());
            return ResultUtils.getResult(ResultInfo.FAILED);
        }
        AssertUtils.isFalse(flag, "上传失败");
        Map<String, Object> resultData = new HashMap<String, Object>();
        resultData.put("saveUrls", timePath + fileName);
        return ResultUtils.getResult(ResultInfo.SUCCESS, null, resultData);
    }

    /**
     * /upload/uploadPhotosAndThumbnail 多图上传并截取缩略图
     *
     * @param file 文件
     * @param type 类型
     * @return savePhotoUrls 图片地址
     * saveThumbnailUrls 缩略图地址
     */
    @PostMapping("/uploadPhotosAndThumbnail")
    public Map<String, Object> uploadPhotosAndThumbnail(MultipartFile[] file, String type) {
        AssertUtils.notNull(type, "类型不能为空");
        StringBuilder files = new StringBuilder();
        StringBuilder temps = new StringBuilder();
        AssertUtils.notNull(type, "类型不能为空");
        AssertUtils.notNull(file, "上传文件为空");
        String timePath = Constants.getUploadUrl().get(type);
        AssertUtils.notNull(timePath, "类型错误");
        AssertUtils.isTrue(StringUtils.isBlank(file[0].getOriginalFilename()), "上传文件为空");
        for (MultipartFile mFile : file) {
            AssertUtils.notNull(mFile, "上传文件为空");
            AssertUtils.isFalse(!RulesUtils.checkIsImage(Objects.requireNonNull(mFile.getOriginalFilename())), "上传文件格式不正确");
            String name = mFile.getOriginalFilename();
            String fileExt = Objects.requireNonNull(name).substring(name.lastIndexOf(".") + 1).toLowerCase();
            String suffix = System.currentTimeMillis() + "_" + new Random().nextInt(1000);
            String fileName = suffix + "." + fileExt;
            String tempName = suffix + "_small." + fileExt;
            boolean flag = false;
            try {
                flag = FileUtils.writeFileToLocal(timePath, fileName, mFile.getInputStream());
            } catch (IOException e) {
                log.info("上传文件发生异常::{}", e.getMessage());
                return ResultUtils.getResult(ResultInfo.FAILED);
            }
            InputStream inputStream = null;
            try {
                inputStream = ImageUtil.thumbnailImage(mFile.getInputStream(), 100, 100, false);
            } catch (IOException e) {
                log.info("截取缩略图发生异常::{}", e.getMessage());
            }
            String fname = timePath + fileName;
            String tname = timePath + tempName;
            if (inputStream == null) {
                tname = "";
            } else {
                FileUtils.writeFileToLocal(timePath, tempName, inputStream);
            }
            AssertUtils.isFalse(flag, "上传失败");
            files.append(",").append(fname);
            temps.append(",").append(tname);
        }
        Map<String, Object> resultData = new HashMap<String, Object>();
        resultData.put("savePhotoUrls", files.substring(1, files.length()));
        resultData.put("saveThumbnailUrls", temps.substring(1, temps.length()));
        return ResultUtils.getResult(ResultInfo.SUCCESS, null, resultData);
    }

}
